package bio_nio_aio.bio.ClinetCommunication;

import java.io.*;
import java.net.Socket;

/**
 * @Auther Jun jie Yi
 * @Date 22:30 2021/8/14
 */
public class ServerReaderSocket extends Thread{

    private Socket socket;

    public ServerReaderSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            //1.重 socket 中读入输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while ((msg = br.readLine()) != null) {
                //2. 给所有的 socket 转发信息
                sendMessageToAllSocket(msg);
            }

        } catch (IOException e) {
            //e.printStackTrace();
            //如果出现异常说明有人下线，这里从集合中删除
            Server.allSocketOnline.remove(socket);
        }
    }

    private void sendMessageToAllSocket(String msg) throws IOException {
        for (Socket socket : Server.allSocketOnline) {
            PrintStream ps = new PrintStream(socket.getOutputStream());
            ps.println(msg);
            ps.close();
        }
    }
}
